package com.sjtu.vfact.textual.model;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import com.sjtu.vfact.textual.util.TextUtil;

public class MasterCollection {
	
	private Set<String> terms;
	private List<MasterTermset> list;
	
	private double coverage;
	private double specificity;
	private double density;
	
	public MasterCollection(){
		list = new ArrayList<MasterTermset>();
		terms = new LinkedHashSet<String>();
	}
	
	public boolean add(TermSet termset, int support, Pair<Integer, Integer> docPair){
		for(MasterTermset mts : list){
			if(mts.getTermset().equals(termset)){
				mts.addDocIdsPair(docPair);
				return false;
			}
		}
		
		List<Pair<Integer, Integer>> pairs = new ArrayList<Pair<Integer,Integer>>();
		pairs.add(docPair);
		int id = list.size() + 1;
		MasterTermset master = new MasterTermset(id,termset, support, pairs);
		list.add(master);
		
		for(String term : termset.getTerms()){
			terms.add(term);
		}
		
		return true;
	}
	
	/**
	 * calculate coverage of the master collection
	 */
	public void calculateCoverage(Set<String> ts){
		Set<String> intersectTerms = TextUtil.<String>intersect(terms, ts);
		double value = ((double) intersectTerms.size()) / ts.size();
		coverage = (double) Math.round(value * 100.0) / 100.0;
	}
	
	/**
	 * calculate specificity of the master collection
	 */
	public void calculateSpecificity(Set<String> ts){
		Set<String> intersectTerms = TextUtil.<String>intersect(terms, ts);
		double value = ((double) intersectTerms.size()) / terms.size();
		specificity = (double) Math.round(value * 100.0) / 100.0;
	}
	
	/**
	 * calculate density of the master collection
	 */
	public void calculateDensity(){
		double value = (2 * coverage * specificity) / (coverage + specificity);
		density = (double) Math.round(value * 100.0) / 100.0;
	}
	
	public int getSize(){
		return list.size();
	}
	
	public double getCoverage() {
		return coverage;
	}

	public double getSpecificity() {
		return specificity;
	}

	public double getDensity() {
		return density;
	}
	
	public Set<String> getTerms(){
		return terms;
	}
	
	public List<MasterTermset> getMasterTermsetList(){
		return list;
	}
	
	public MasterTermset getMasterTermset(int index){
		return list.get(index);
	}
	
	public TermSet getTermset(int index){
		return list.get(index).getTermset();
	}
	
	public List<TermSet> getAllTermsets(){
		List<TermSet> keys = new ArrayList<TermSet>();
		for(MasterTermset mts : list){
			keys.add(mts.getTermset());
		}
		
		return keys;
	}
	
	public Set<Integer> getAllIds(){
		Set<Integer> ids = new LinkedHashSet<Integer>();
		for(MasterTermset mts : list){
			ids.add(mts.getId());
		}
		
		return ids;
	}
	
	@Override
	public String toString(){
		String s = "";
		for(MasterTermset mts : list){
			s += "[" + mts.toString() + "]\n";
		}
		
		return s;
	}
	
}
